//HTML 模板渲染
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type UserInfo struct {
	ID        uint64    `gorm:"primary_key;AUTO_INCREMENT" json:"id"`
	Name      string    `gorm:"type:varchar(30);not null" json:"name" form:"name" binding:"required"`
	Age       int64     `gorm:"type:tinyint(3);not null;default:0"  json:"age"  form:"age"  binding:"required"`
	Gender    string    `gorm:"type:varchar(6);not null"  json:"gender" form:"gender" binding:"required"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

var Db *gorm.DB

//数据库连接
func init() {
	driverName := "mysql"
	host := "127.0.0.1"
	port := "3306"
	database := "galen"
	username := "root"
	password := "root"
	charset := "utf8"
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=Local",
		username,
		password,
		host,
		port,
		database,
		charset,
	)

	//db, err := gorm.Open("mysql","user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	//自动创建数据表
	db.AutoMigrate(&UserInfo{})

	Db = db
}

func main() {
	route := gin.Default()

	//加载模板
	route.LoadHTMLGlob("templates/**/*")

	//加载静态文件
	route.Static("/assets", "./assets")

	//定义路由
	r := route.Group("/posts")
	{
		//列表页
		r.GET("/index", postsIndex)

		//详情页
		r.GET("/detail", postsDetail)

		//添加页面
		r.GET("/create", postsCreate)
		//表单提交
		r.POST("/createAdd", postsCreateAdd)

		//修改页面
		r.GET("/update", postsUpdate)
		r.POST("/updateAdd", postsUpdateAdd)

		//删除操作
		r.GET("/delete", postDelete)
	}

	route.Run(":8080")
}

func postsIndex(c *gin.Context) {
	var users []UserInfo
	result := Db.Order("id desc").Find(&users)
	if result.Error != nil {
		c.JSON(500, gin.H{"error": result.Error.Error()})
		return
	}

	c.HTML(http.StatusOK, "posts/index.html", gin.H{
		"title":   "网站首页",
		"active1": "active",
		"active2": "",
		"data":    users,
	})
}

func postsDetail(c *gin.Context) {
	id := c.DefaultQuery("id", "")

	//定义结果集数组
	var info UserInfo
	Db.Where("id = ?", id).Find(&info)

	c.HTML(http.StatusOK, "posts/detail.html", gin.H{
		"title":   "详情页",
		"active1": "active",
		"active2": "",
		"info":    info,
	})
}

func postsCreate(c *gin.Context) {
	c.HTML(http.StatusOK, "posts/create.html", gin.H{
		"title":   "新增页",
		"active1": "",
		"active2": "active",
	})
}

func postsCreateAdd(c *gin.Context) {
	var data UserInfo
	if err := c.Bind(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	result := Db.Create(&data)
	if result.Error != nil {
		c.JSON(500, gin.H{"error ": "新增错误—" + result.Error.Error()})
		return
	}

	c.Redirect(301, "/posts/index")
}

func postsUpdate(c *gin.Context) {
	id := c.DefaultQuery("id", "")

	//定义结果集数组
	var info UserInfo
	Db.Where("id = ?", id).Find(&info)

	c.HTML(http.StatusOK, "posts/update.html", gin.H{
		"title":   "修改页",
		"active1": "active",
		"active2": "",
		"info":    info,
	})
}

func postsUpdateAdd(c *gin.Context) {
	var data UserInfo
	if err := c.Bind(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	id := c.DefaultQuery("id", "")
	result := Db.Model(&data).Where("id = ?", id).Updates(&data)
	if result.Error != nil {
		c.JSON(500, gin.H{"error": "更新错误-" + result.Error.Error()})
	}

	c.Redirect(301, "/posts/index")
}

func postDelete(c *gin.Context) {
	id := c.DefaultQuery("id", "")

	var user UserInfo
	Db.Delete(user, "id = ?", id)

	c.Redirect(301, "/posts/index")
}
